<template>
    <div class="root flex-col">
        <div class="flex-row">
            <el-button type="primary" @click="createAnimationDialogVisible = true">创建动画</el-button>
        </div>
        <!-- <div class="animation-list flex-row">
            <div class="animation-item flex-col" v-for="item,i in animations" :key="i">
                <div class="cover" :style="{backgroundImage:`url(${getAnimationImageUrl(item)})`}"></div>
                <div class="name">{{item.name}}</div>
            </div>
        </div> -->
        <AnimationList :animations="animations" @-picture-card-preview="handlePictureCardPreview" @remove-picture="onRemoveAnimation"/>
    </div>
    <el-dialog v-model="createAnimationDialogVisible" width="600" title="创建序列图动画">
        <el-form label-width="100px" ref="animationRef" :model="ruleForm" :rules="rules">
            <el-form-item label="动画名称：" prop="name">
                <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="尺寸：" required>
                <el-col :span="2">宽：</el-col>
                <el-col :span="8">
                    <el-input-number :min="1" v-model="ruleForm.width"></el-input-number>
                </el-col>
                <el-col :span="2" style="margin-left: 10px">高：</el-col>
                <el-col :span="8">
                    <el-input-number :min="1" v-model="ruleForm.height"></el-input-number>
                </el-col>
            </el-form-item>
            <el-form-item label="">
                <span class="des">宽为动画显示的宽度，一般为序列图的宽度，当宽度小于序列图宽度时，序列图会被裁剪。高也同理。</span>
            </el-form-item>
            <el-form-item label="原点：" required>
                <el-col :span="3">左(x)：</el-col>
                <el-col :span="8">
                    <el-input-number :min="0" v-model="ruleForm.originx"></el-input-number>
                </el-col>
                <el-col :span="3" style="margin-left: 10px">顶(y)：</el-col>
                <el-col :span="8">
                    <el-input-number :min="0" v-model="ruleForm.originy"></el-input-number>
                </el-col>
            </el-form-item>
            <el-form-item label="文件名：" prop="fileName">
                <el-col :span="8">
                    <el-input v-model="ruleForm.fileName"></el-input>
                </el-col>
            </el-form-item>
            <el-form-item label="开始编号：" required>
                <!-- <el-col :span="4">开始编号：</el-col> -->
                <el-col :span="8">
                    <el-input-number :min="0" v-model="ruleForm.startNumber"></el-input-number>
                </el-col>
                <el-col :span="4" style="margin-left: 10px">结束编号：</el-col>
                <el-col :span="8">
                    <el-input-number :min="1" v-model="ruleForm.endNumber"></el-input-number>
                </el-col>
            </el-form-item>
            <el-form-item label="编号位数：" prop="numberDigits">
                <el-col :span="8">
                    <el-input-number :min="1" v-model="ruleForm.numberDigits"></el-input-number>
                </el-col>
            </el-form-item>
            <el-form-item label="动画帧率：" prop="fps">
                <el-col :span="8">
                    <el-input-number :min="1" v-model="ruleForm.fps"></el-input-number>
                </el-col>
            </el-form-item>
            <el-form-item label="序列图：">
                <el-col :span="12">
                    <el-upload
                        ref="upload"
                        accept="image/*"
                        :multiple="true"
                        :auto-upload="false"
                        :action="uploadUrl"
                        :data="ruleForm"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove"
                        :on-success="handleSuccess" >
                        <!-- <i class="el-icon-plus"><el-icon><Plus /></el-icon></i> -->
                        <template #trigger>
                            <el-button type="primary">选择文件</el-button>
                        </template>
                        <el-button class="ml-3" type="success" @click="submitUpload" style="margin-left: 10px">
                            上传
                        </el-button>
                    </el-upload>
                </el-col>
            </el-form-item>
        </el-form>
        <template #footer></template>
    </el-dialog>
    <el-dialog v-model="previewDialogVisible">
        <SpriteAnimation :data="animationData" :width="animationData.width" :height="animationData.height"></SpriteAnimation>
        <!-- <img w-full :src="dialogImageUrl" alt="Preview Image" class="pre-view" ref="preAnimationView" @load="handlePreviewLoaded"/> -->
    </el-dialog>
</template>
<script lang="ts">
import Global from '@/Global'
import { defineComponent, reactive, ref,onMounted } from 'vue'
import { FormInstance, FormRules, UploadInstance, UploadProps } from 'element-plus'
import ApiHelper from '@/api/ApiHelper'
import SourceModel from '@/game/model/SourceModel'
import { createRandomString } from '@/utils/tools'
interface RuleForm {
  name: string
  path: string
  ext: string
  originx: number
  originy: number
  width: number
  height: number
  /** 文件名（不含序列编号） */
  fileName: string
  startNumber: number
  endNumber: number
  numberDigits: number
  fps:number
  /** 文件hash（上传序列图时会创建一个子文件夹，命名为hash，用来区分每批次上传的序列图） */
  hash:string
}
export default defineComponent({
    name: 'AnimationView',
    setup(props, ctx) {
        const baseUrl=process.env.VUE_APP_BASE_API
        const createAnimationDialogVisible = ref(false)
        const previewDialogVisible = ref(false)
        const uploadUrl=ref(Global.getInstance().baseUrl+'/upload_sequence_image')
        const dialogImageUrl = ref('')
        const upload = ref<UploadInstance>()
        const animationRef=ref<FormInstance>()
        //预览图
        const preAnimationView = ref()
        const ruleForm = reactive<RuleForm>({
            name: '',
            path:'',
            ext:'',
            originx: 0,
            originy: 0,
            width: 100,
            height: 100,
            fileName: '',
            startNumber: 0,
            endNumber: 10,
            numberDigits: 2,
            fps:60,
            hash:createRandomString()
        })
        //表单校验规则
        const rules = reactive<FormRules<RuleForm>>({
            name: [
                { required: true, message: '请输入动画名称', trigger: 'blur' }
            ],
            originx: [
                { required: true, message: '请输入原点x', trigger: 'blur' }
            ],
            originy: [
                { required: true, message: '请输入原点y', trigger: 'blur' }
            ],
            width: [
                { required: true, message: '请输入宽度', trigger: 'blur' }
            ],
            height: [
                { required: true, message: '请输入高度', trigger: 'blur' }
            ],
            fileName: [
                { required: false, message: '请输入文件名', trigger: 'blur' }
            ],
            startNumber: [
                { required: true, message: '请输入开始编号', trigger: 'blur' }
            ],
            endNumber: [
                { required: true, message: '请输入结束编号', trigger: 'blur' }
            ],
            numberDigits: [
                { required: true, message: '请输入编号位数', trigger: 'blur' }
            ],
            fps: [
                { required: true, message: '请输入动画帧率', trigger: 'blur' }
            ]
        })
        //
        const animationData=reactive<SourceModel>(new SourceModel)
        //let ani=0,aniItem=null
        const animations=reactive([])
        const handlePictureCardPreview = (item) => {
            /*aniItem=item
            ani=item.start
            const str=getAnimationImageUrl(item,ani)
            console.log(str)
            dialogImageUrl.value = str*/
            previewDialogVisible.value = true
            animationData.path=item.path
            animationData.ext=item.ext
            animationData.start=item.start
            animationData.end=item.end
            animationData.digits=item.digits
            animationData.width=item.width
            animationData.height=item.height
            animationData.originx=item.originx
            animationData.originy=item.originy
            animationData.fps=item.fps
        }
        const handleRemove = (item) => {
            //
        }
        // 上传成功回调
        let count=0
        const handleSuccess:UploadProps['onSuccess'] = (
            response,
            uploadFile,
            uploadFiles
        )=>{
            //console.log(response)
            if(response.StatusCode=='success'){
                const pattern = /\.(\w*)$/;
                ruleForm.path=response.data.path
                ruleForm.ext=uploadFile.name.match(pattern)[0]
            }
            //console.log(pattern.test(uploadFile.name))
            //console.log(uploadFile.name.match(pattern)[0])
            count++
            if(count==uploadFiles.length){
                // 上传完成，调用后端接口创建动画
                ApiHelper.getInstance().addAnimation(ruleForm).then(res=>{
                    //console.log(res)
                    createAnimationDialogVisible.value=false
                    getAnimationList()
                })
            }
        }
        const submitUpload = () => {
            //console.log(animationRef.value)
            animationRef.value?.validate((valid:any)=> {
                if (valid) {
                    upload.value!.submit()
                } else {
                    //return false
                }
            })
            
        }
        const getAnimationImageUrl=(item:any,index=0):string=>{
            let str=''
            for(let i=0;i<item.digits;i++){
                str+='0'
            }
            str+=index
            str=str.substring(str.length-item.digits)
            return baseUrl+item.path+str+item.ext
        }
        const getAnimationList=()=>{
            ApiHelper.getInstance().getAnimations().then(res=>{
                console.log(res)
                animations.length=0
                res.forEach((item:any)=>{
                    animations.push(item)
                })
            })
        }
        /*const handlePreviewLoaded=()=>{
            console.log('加载完成！')
            //console.log(preAnimationView.value)
            ani++
            if(ani<=aniItem.end){
                const str=getAnimationImageUrl(aniItem,ani)
                console.log(str)
                dialogImageUrl.value = str
            }else{
                // 循环播放
                
            }
            
        }*/
        const onRemoveAnimation=(item)=>{
            //console.log(item)
            ApiHelper.getInstance().deleteAnimation(item.id!).then(res=>{
                console.log(res)
                getAnimationList()
            }).catch(err=>{
                console.log(err)
            })
        }
        onMounted(()=>{
            getAnimationList()
        })
        return {
            upload,
            uploadUrl,
            createAnimationDialogVisible,
            previewDialogVisible,
            dialogImageUrl,
            animationRef,
            ruleForm,
            rules,
            animations,
            preAnimationView,
            animationData,
            handlePictureCardPreview,
            handleRemove,
            handleSuccess,
            submitUpload,
            onRemoveAnimation
        }
    },
})
</script>
<style lang="less" scoped>
.root{
  width: 100%;
  height: 100%;
  padding: 20px;
}
.des{
    color:rgba(0, 0, 0, 0.267);
}
</style>